<template>
  <div class="p-4">
    <form @submit.prevent="handleSubmit" class="space-y-4">
      <!-- 用户名输入 -->
      <div class="form-control">
        <label class="label">
          <span class="label-text">用户名</span>
        </label>
        <input
          type="text"
          v-model="formData.username"
          class="input input-bordered"
          :class="{ 'input-error': errors.username }"
          @blur="validateField('username')"
        />
        <label class="label" v-if="errors.username">
          <span class="label-text-alt text-error">{{ errors.username }}</span>
        </label>
      </div>

      <!-- 邮箱输入 -->
      <div class="form-control">
        <label class="label">
          <span class="label-text">邮箱</span>
        </label>
        <input
          type="email"
          v-model="formData.email"
          class="input input-bordered"
          :class="{ 'input-error': errors.email }"
          @blur="validateField('email')"
        />
        <label class="label" v-if="errors.email">
          <span class="label-text-alt text-error">{{ errors.email }}</span>
        </label>
      </div>

      <!-- 手机号码输入 -->
      <div class="form-control">
        <label class="label">
          <span class="label-text">手机号码</span>
        </label>
        <input
          type="tel"
          v-model="formData.phone"
          class="input input-bordered"
          :class="{ 'input-error': errors.phone }"
          @blur="validateField('phone')"
        />
        <label class="label" v-if="errors.phone">
          <span class="label-text-alt text-error">{{ errors.phone }}</span>
        </label>
      </div>

      <!-- 提交按钮 -->
      <button type="submit" class="btn btn-primary w-full">提交</button>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { required, email, phoneNumber, minLength } from '@/utils/validation'

// 表单数据
const formData = reactive({
  username: '',
  email: '',
  phone: '',
})

// 错误信息
const errors = reactive({
  username: '',
  email: '',
  phone: '',
})

// 验证规则
const validationRules = {
  username: [required, minLength(3)],
  email: [required, email],
  phone: [required, phoneNumber],
}

// 验证单个字段
const validateField = (field: keyof typeof formData) => {
  const rules = validationRules[field]
  let isValid = true

  for (const rule of rules) {
    const result = rule(formData[field])
    if (result !== true) {
      errors[field] = result as string
      isValid = false
      break
    }
  }

  if (isValid) {
    errors[field] = ''
  }

  return isValid
}

// 验证所有字段
const validateForm = () => {
  let isValid = true
  for (const field in formData) {
    if (!validateField(field as keyof typeof formData)) {
      isValid = false
    }
  }
  return isValid
}

// 提交表单
const handleSubmit = () => {
  if (validateForm()) {
    console.log('表单验证通过', formData)
    // 这里可以添加提交逻辑
  } else {
    console.log('表单验证失败')
  }
}
</script>
